//
//  ViewController.m
//  VideoCompositon
//
//  Created by 郭永峰 on 2023/4/23.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "VideoEditFile.h"

@interface ViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (strong, nonatomic) AVPlayer *player;
@property (strong, nonatomic) AVPlayerItem *playerItem;
@property (strong, nonatomic) id timeObserver; // 添加时间观察者属性
@property (strong, nonatomic) UIView *playerView;
@property (strong, nonatomic) UIView *toolbarView;
@property (strong, nonatomic) AVPlayerLayer *playerLayer;

@property (strong, nonatomic) AVMutableComposition *composition;
@property (strong, nonatomic) AVMutableVideoComposition *videoComposition;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupPlayer];

    NSURL * url1 = [[NSBundle mainBundle] URLForResource:@"simon" withExtension:@"mp4"];
    NSURL * url2 = [[NSBundle mainBundle] URLForResource:@"Test" withExtension:@"mp4"];
    dispatch_async(dispatch_get_global_queue(0, 0),^{
//        UIImageOrientationUp,            // default orientation
//        UIImageOrientationDown,          // 180 deg rotation
//        UIImageOrientationLeft,          // 90 deg CCW
//        UIImageOrientationRight,         // 90 deg CW
//        UIImageOrientationUpMirrored,    // as above but image mirrored along other axis. horizontal flip
//        UIImageOrientationDownMirrored,  // horizontal flip
//        UIImageOrientationLeftMirrored,  // vertical flip
//        UIImageOrientationRightMirrored, // vertical flip

        [self mergeVideos:@[url1,url2] completion:^(NSURL *outputURL, NSError *error) {
            NSLog(@"%@,%@",outputURL,error);
        }];
    });
//
//    [self huaZhongHuaMergeVideos:@[url1,url2] completion:^(NSURL *outputURL, NSError *error) {
//        NSLog(@"画中画 %@,%@",outputURL,error);
//    }];
}

// 在视图消失时清理资源
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    // 移除时间观察者
    if (self.timeObserver) {
        [self.player removeTimeObserver:self.timeObserver];
        self.timeObserver = nil;
    }
    
    [self.player pause];
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor blackColor];
    
    // 播放器视图
    self.playerView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, self.view.bounds.size.width, 400)];
    [self.view addSubview:self.playerView];
    
    // 工具栏
    self.toolbarView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 120, self.view.bounds.size.width, 120)];
    self.toolbarView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.toolbarView];
    [self setupToolbarButtons];
}

// 添加滤镜按钮到工具栏
- (void)setupToolbarButtons {
    NSArray *titles = @[@"导出"];
    CGFloat buttonWidth = 70;
    CGFloat buttonHeight = 60;
    CGFloat spacing = 5;
    
    UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.toolbarView.bounds.size.width, 120)];
    [self.toolbarView addSubview:scrollView];
    
    for (NSInteger i = 0; i < titles.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(spacing + i * (buttonWidth + spacing), 10, buttonWidth, buttonHeight);
        [button setTitle:titles[i] forState:UIControlStateNormal];
        button.tag = i;
        button.backgroundColor = [UIColor systemBlueColor];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        button.titleLabel.numberOfLines = 2;
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        button.layer.cornerRadius = 8;
        [button addTarget:self action:@selector(toolbarButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        [scrollView addSubview:button];
        scrollView.contentSize = CGSizeMake(CGRectGetMaxX(button.frame) + spacing, buttonHeight);
    }
}

- (void)toolbarButtonTapped:(UIButton *)sender {
    switch (sender.tag) {
        case 0: [self exportVideo]; break;
        default: break;
    }
}

// 修改播放器设置方法
- (void)setupPlayer {
    
    if(self.composition == nil){
        NSLog(@"❌ 播放器项未初始化");
        return;
    }
    
    // 创建播放项目
    self.playerItem = [AVPlayerItem playerItemWithAsset:self.composition];
    if (!self.playerItem) {
        NSLog(@"❌ 创建播放项目失败");
        return;
    }
    
    // 设置视频组合 - 这是关键步骤！
    self.playerItem.videoComposition = self.videoComposition;
    NSLog(@"✅ 设置播放项目的视频组合");
    
    // 设置音频时间间距算法
    self.playerItem.audioTimePitchAlgorithm = AVAudioTimePitchAlgorithmVarispeed;
    
    // 创建播放器
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    if (!self.player) {
        NSLog(@"❌ 创建播放器失败");
        return;
    }
    
    if(self.playerLayer){
        [self.playerLayer removeFromSuperlayer];
        self.playerLayer = nil;
    }
    
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = self.playerView.bounds;
    // 让视频充满整个画布
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.playerView.layer addSublayer:self.playerLayer];
    
    NSLog(@"✅ 播放器创建成功");
    
    // 开始播放
    [self.player play];
    NSLog(@"🎬 开始播放");
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        if (object == self.player) {
            NSLog(@"🎮 播放器状态: %ld", (long)self.player.status);
            if (self.player.status == AVPlayerStatusReadyToPlay) {
                [self.player play];
                NSLog(@"🎬 播放器准备就绪，开始播放");
            }
        } else if (object == self.playerItem) {
            NSLog(@"🎮 播放项目状态: %ld", (long)self.playerItem.status);
            if (self.playerItem.status == AVPlayerItemStatusReadyToPlay) {
                // 移除监听，避免重复触发
                [self.playerItem removeObserver:self forKeyPath:@"status"];
                [self.player play];
                NSLog(@"🎬 播放项目准备就绪，开始播放");
            } else if (self.playerItem.status == AVPlayerItemStatusFailed) {
                NSLog(@"❌ 播放项目失败: %@", self.playerItem.error);
            }
        }
    }
}

// 两个视频拼接
- (void)mergeVideos:(NSArray<NSURL *> *)videoURLs
          completion:(void (^)(NSURL *outputURL, NSError *error))completion {
    
    if (videoURLs.count == 0) {
        NSError *error = [NSError errorWithDomain:@"MergeVideosError" code:400 userInfo:@{NSLocalizedDescriptionKey: @"没有提供视频文件"}];
        completion(nil, error);
        return;
    }

    // 创建合成器
    AVMutableComposition *composition = [AVMutableComposition composition];
    CMTime insertTime = kCMTimeZero;
    
    // 创建多个视频轨
    NSArray * videoTrackes = [VideoEditFile addUrl:videoURLs toComposition:composition atTime:insertTime];
    
    // 创建一个音频轨
    AVMutableCompositionTrack *audioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];

    // 读取第一个资源的音频轨
    // 获取并插入音频轨道
    AVURLAsset *asset = [AVURLAsset assetWithURL:videoURLs.firstObject];
    AVAssetTrack *audioTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] firstObject];
    if (audioTrack) {
        NSError *audioError = nil;
        [audioCompositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset.duration) ofTrack:audioTrack atTime:insertTime error:&audioError];
        
        if (audioError) {
            NSLog(@"音频插入失败: %@", audioError);
        }
    }
    
    // 创建播放指令
    AVMutableVideoComposition * videoComposition = [VideoEditFile compositionWithTracks:videoTrackes timeRange:CMTimeRangeMake(kCMTimeZero, composition.duration) Opacity:@[@0.5,@1] renderSize:CGSizeMake(1280, 760)];
    
    self.composition = composition;
    self.videoComposition = videoComposition;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self setupPlayer];
    });
}

// 确保导出时也应用滤镜
- (void)exportVideo {
    if (!self.composition) return;
    
    // 创建导出会话
    NSArray *supportedPresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:self.composition];
    NSString *presetName = AVAssetExportPresetHighestQuality;
    
    if (![supportedPresets containsObject:presetName]) {
        if ([supportedPresets containsObject:AVAssetExportPreset1280x720]) {
            presetName = AVAssetExportPreset1280x720;
        } else if (supportedPresets.count > 0) {
            presetName = supportedPresets.firstObject;
        } else {
            NSError *error = [NSError errorWithDomain:@"ExportError" code:-11838 userInfo:@{NSLocalizedDescriptionKey: @"没有支持的导出格式"}];
            [self showExportError:error];
            return;
        }
    }
    
    AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:self.composition presetName:presetName];
    
    // 设置输出路径
    NSString *outputFileName = [NSString stringWithFormat:@"merged_video_%@.mp4", @((NSInteger)[[NSDate date] timeIntervalSince1970])];
    NSURL *outputURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:outputFileName]];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:outputURL.path]) {
        [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
    }
    
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeMPEG4;
    exportSession.shouldOptimizeForNetworkUse = YES;
    exportSession.videoComposition = self.videoComposition; // 设置视频合成
    
    // 导出
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (exportSession.status) {
                case AVAssetExportSessionStatusCompleted:
                    // 保存到相册
                    [VideoEditFile saveVideoToPhotoLibrary:outputURL completion:^(BOOL success, NSError *saveError) {
                        if (saveError) {
                            NSLog(@"保存到相册失败: %@", saveError);
                        } else {
                            NSLog(@"视频已成功保存到相册");
                        }
                    }];
                    break;
                case AVAssetExportSessionStatusFailed:
                    [self showExportError:exportSession.error];
                    break;
                case AVAssetExportSessionStatusCancelled:
                    [self showExportError:[NSError errorWithDomain:@"ExportCancelled" code:499 userInfo:nil]];
                    break;
                default:
                    [self showExportError:[NSError errorWithDomain:@"ExportError" code:500 userInfo:nil]];
                    break;
            }
        });
    }];
}

// 方向变换方法
- (CGAffineTransform)transformForOrientation:(UIImageOrientation)orientation naturalSize:(CGSize)naturalSize {
    switch (orientation) {
        case UIImageOrientationUp:
            return CGAffineTransformIdentity;
        case UIImageOrientationDown:
            return CGAffineTransformMake(-1, 0, 0, -1, naturalSize.width, naturalSize.height);
        case UIImageOrientationLeft:
            return CGAffineTransformMake(0, -1, 1, 0, 0, naturalSize.width);
        case UIImageOrientationRight:
            return CGAffineTransformMake(0, 1, -1, 0, naturalSize.height, 0);
        default:
            return CGAffineTransformIdentity;
    }
}

- (void)showExportError:(NSError *)error {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"导出失败" message:error.localizedDescription preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

//
//// 辅助方法：处理视频方向
//- (AVMutableVideoComposition *)fixedCompositionWithAsset:(AVAsset *)asset {
//    AVMutableVideoComposition *videoComposition = [AVMutableVideoComposition videoComposition];
//
//    AVAssetTrack *videoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] firstObject];
//    if (!videoTrack) return nil;
//
//    CGSize naturalSize = videoTrack.naturalSize;
//    CGAffineTransform preferredTransform = videoTrack.preferredTransform;
//
//    // 如果视频需要旋转
//    if (preferredTransform.a == 0 && preferredTransform.d == 0 &&
//        (preferredTransform.b == 1.0 || preferredTransform.b == -1.0) &&
//        (preferredTransform.c == 1.0 || preferredTransform.c == -1.0)) {
//
//        naturalSize = CGSizeMake(naturalSize.height, naturalSize.width);
//    }
//
//    videoComposition.renderSize = naturalSize;
//    videoComposition.frameDuration = CMTimeMake(1, 30);
//
//    AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
//    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
//
//    AVMutableVideoCompositionLayerInstruction *layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
//    [layerInstruction setTransform:preferredTransform atTime:kCMTimeZero];
//
//    instruction.layerInstructions = @[layerInstruction];
//    videoComposition.instructions = @[instruction];
//
//    return videoComposition;
//}

//
//- (void)huaZhongHuaMergeVideos:(NSArray<NSURL *> *)videoURLs completion:(void (^)(NSURL *outputURL, NSError *error))completion {
//    if (videoURLs.count == 0) {
//        NSError *error = [NSError errorWithDomain:@"MergeVideosError" code:400 userInfo:@{NSLocalizedDescriptionKey: @"没有提供视频文件"}];
//        completion(nil, error);
//        return;
//    }
//
//    AVMutableComposition *composition = [AVMutableComposition composition];
//    CMTime insertTime = kCMTimeZero;
//
//    // 创建视频和音频轨道
//    AVMutableCompositionTrack *videoCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
//    AVMutableCompositionTrack *audioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
//
//    // 获取第一个视频的方向和尺寸，用于统一输出
//    AVURLAsset *firstAsset = [AVURLAsset assetWithURL:videoURLs.firstObject];
//    AVAssetTrack *firstVideoTrack = [[firstAsset tracksWithMediaType:AVMediaTypeVideo] firstObject];
//    CGAffineTransform preferredTransform = firstVideoTrack.preferredTransform;
//
//    for (NSURL *videoURL in videoURLs) {
//        @autoreleasepool {
//            AVURLAsset *asset = [AVURLAsset assetWithURL:videoURL];
//
//            // 等待资源加载完成
//            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//            __block BOOL loadSuccess = YES;
//
//            [asset loadValuesAsynchronouslyForKeys:@[@"tracks", @"duration"] completionHandler:^{
//                NSError *error = nil;
//                AVKeyValueStatus tracksStatus = [asset statusOfValueForKey:@"tracks" error:&error];
//                AVKeyValueStatus durationStatus = [asset statusOfValueForKey:@"duration" error:&error];
//
//                if (tracksStatus != AVKeyValueStatusLoaded || durationStatus != AVKeyValueStatusLoaded || error) {
//                    loadSuccess = NO;
//                }
//                dispatch_semaphore_signal(semaphore);
//            }];
//
//            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//
//            if (!loadSuccess) {
//                NSError *error = [NSError errorWithDomain:@"AssetLoadError" code:500 userInfo:@{NSLocalizedDescriptionKey: @"视频资源加载失败"}];
//                completion(nil, error);
//                return;
//            }
//
//            // 获取视频轨道
//            AVAssetTrack *videoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] firstObject];
//            if (!videoTrack) {
//                NSError *error = [NSError errorWithDomain:@"InvalidVideoError" code:501 userInfo:@{NSLocalizedDescriptionKey: @"视频中没有视频轨道"}];
//                completion(nil, error);
//                return;
//            }
//
//            // 插入视频轨道
//            NSError *videoError = nil;
//            CMTimeRange timeRange = CMTimeRangeMake(kCMTimeZero, asset.duration);
//            [videoCompositionTrack insertTimeRange:timeRange ofTrack:videoTrack atTime:insertTime error:&videoError];
//
//            if (videoError) {
//                completion(nil, videoError);
//                return;
//            }
//
//            // 获取并插入音频轨道
//            AVAssetTrack *audioTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] firstObject];
//            if (audioTrack) {
//                NSError *audioError = nil;
//                [audioCompositionTrack insertTimeRange:timeRange ofTrack:audioTrack atTime:insertTime error:&audioError];
//
//                if (audioError) {
//                    NSLog(@"音频插入失败: %@", audioError);
//                    // 继续处理，不返回错误
//                }
//            }
//
//            insertTime = CMTimeAdd(insertTime, asset.duration);
//        }
//    }
//
//    // 检查合成是否有效
//    if (CMTimeGetSeconds(composition.duration) == 0) {
//        NSError *error = [NSError errorWithDomain:@"CompositionError" code:-11838 userInfo:@{NSLocalizedDescriptionKey: @"合成视频时长为0"}];
//        completion(nil, error);
//        return;
//    }
//
//    // 设置视频方向（统一使用第一个视频的方向）
//    videoCompositionTrack.preferredTransform = preferredTransform;
//
//    // 创建导出会话
//    NSArray *supportedPresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:composition];
//    NSString *presetName = AVAssetExportPresetHighestQuality;
//
//    if (![supportedPresets containsObject:presetName]) {
//        // 尝试其他预设
//        if ([supportedPresets containsObject:AVAssetExportPreset1280x720]) {
//            presetName = AVAssetExportPreset1280x720;
//        } else if ([supportedPresets containsObject:AVAssetExportPreset960x540]) {
//            presetName = AVAssetExportPreset960x540;
//        } else if (supportedPresets.count > 0) {
//            presetName = supportedPresets.firstObject;
//        } else {
//            NSError *error = [NSError errorWithDomain:@"ExportError" code:-11838 userInfo:@{NSLocalizedDescriptionKey: @"没有支持的导出格式"}];
//            completion(nil, error);
//            return;
//        }
//    }
//
//    AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:composition presetName:presetName];
//
//    // 设置输出路径
//    NSString *outputFileName = [NSString stringWithFormat:@"hzh_merged_video_%@.mp4", [NSDate date].description];
//    NSURL *outputURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:outputFileName]];
//
//    // 删除已存在的文件
//    if ([[NSFileManager defaultManager] fileExistsAtPath:outputURL.path]) {
//        [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
//    }
//
//    exportSession.outputURL = outputURL;
//    exportSession.outputFileType = AVFileTypeMPEG4;
//    exportSession.shouldOptimizeForNetworkUse = YES;
//
//
//
//
//    // 导出
//    [exportSession exportAsynchronouslyWithCompletionHandler:^{
//        dispatch_async(dispatch_get_main_queue(), ^{
//            switch (exportSession.status) {
//                case AVAssetExportSessionStatusCompleted:
//                    completion(outputURL, nil);
//                    break;
//                case AVAssetExportSessionStatusFailed:
//                    NSLog(@"导出失败: %@", exportSession.error);
//                    completion(nil, exportSession.error);
//                    break;
//                case AVAssetExportSessionStatusCancelled:
//                    completion(nil, [NSError errorWithDomain:@"ExportCancelled" code:499 userInfo:nil]);
//                    break;
//                default:
//                    completion(nil, [NSError errorWithDomain:@"ExportUnknownError" code:500 userInfo:nil]);
//                    break;
//            }
//        });
//    }];
//}

@end
